const app = getApp();
import { get, post } from '../../../../utils/request';
import auth from '../../../../utils/auth';

Page({
  data: {
    availableOrders: [],
    loading: true,
    page: 1,
    size: 10,
    hasMore: true,
    selectedOrder: null,
    showConfirmModal: false
  },

  onLoad() {
    this.checkPermission();
    this.loadAvailableOrders();
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      page: 1,
      hasMore: true,
      availableOrders: []
    });
    this.loadAvailableOrders().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreOrders();
    }
  },

  // 检查权限
  checkPermission() {
    // 只允许服务人员访问
    if (!auth.isProvider()) {
      wx.showToast({
        title: '您不是服务人员，无法访问此页面',
        icon: 'none'
      });

      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 加载可接取的订单
  loadAvailableOrders() {
    this.setData({ loading: true });
    return get('/api/orders/available', {
      current: this.data.page,
      size: this.data.size
    })
      .then(res => {
        if (res.code === 0 && res.data) {
          const newOrders = res.data.records || [];
          this.setData({
            availableOrders: this.data.page === 1 ? newOrders : [...this.data.availableOrders, ...newOrders],
            hasMore: newOrders.length >= this.data.size
          });

        } else {
          wx.showToast({
            title: res.message || '获取订单失败',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        console.error('获取可接取订单失败:', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      })
      .finally(() => {
        this.setData({ loading: false });
      });
  },

  // 加载更多订单
  loadMoreOrders() {
    this.setData({
      page: this.data.page + 1
    });
    this.loadAvailableOrders();
  },

  // 显示订单详情
  showOrderDetail(e) {
    const orderId = e.currentTarget.dataset.id;
    const order = this.data.availableOrders.find(item => item.id === orderId);

    if (order) {
      this.setData({
        selectedOrder: order,
        showConfirmModal: true
      });
    }
  },

  // 关闭确认弹窗
  closeConfirmModal() {
    this.setData({
      showConfirmModal: false
    });
  },

  // 接受订单
  acceptOrder() {
    if (!this.data.selectedOrder) {
      return;
    }

    const orderId = this.data.selectedOrder.id;

    // 调用接单接口
    post(`/api/orders/accept/${orderId}`)
      .then(res => {
        if (res.code === 0 && res.data) {
          wx.showToast({
            title: '接单成功',
            icon: 'success'
          });

          // 关闭弹窗
          this.setData({
            showConfirmModal: false
          });

          // 刷新订单列表
          setTimeout(() => {
            this.setData({
              page: 1,
              availableOrders: []
            });
            this.loadAvailableOrders();
          }, 1000);
        } else {
          wx.showToast({
            title: res.message || '接单失败',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        console.error('接单失败:', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      });
  },

  // 格式化时间
  formatTime(timeString) {
    if (!timeString) return '';
    return timeString.replace('T', ' ').substring(0, 16);
  }
}) 